package com.bootdo.acitvity.DDD.domain;


import com.bootdo.acitvity.DDD.domain.entity.ChannelFrozenStock;
import com.bootdo.acitvity.DDD.domain.entity.ChannelLockedStock;
import com.bootdo.acitvity.DDD.domain.entity.ChannelSoldAmount;
import freemarker.template.utility.DateUtil;
import lombok.Data;
import lombok.Getter;
import lombok.experimental.Accessors;

import java.util.*;

@Data
@Accessors(chain = true)
public class ChannelStock {


    public ChannelStock(Long channelId){
        this.channelId = channelId;
        lastLockRestoredTime  = new Date();
    }

    //  有 ID 标识，通过 ID 判断相等性，ID 在聚合内唯一
    //  实体一般会持久化，但与数据库持久化对象不一定是一对一的关系
    //  它依附于聚合根，其生命周期由聚合根管理

    /**
     * 渠道id --> id标识[唯一标识符]
     */
    @Getter
    private Long channelId;

    /**
     * 渠道锁定库存  -->值对象
     */
    private ChannelLockedStock channelLockedStock;

    /**
     * 渠道冻结库存  -->值对象
     */
    private List<ChannelFrozenStock> channelFrozenStocks = new LinkedList<>();

    /**
     * 销量  -->值对象
     */
    private ChannelSoldAmount channelSoldAmounts = new ChannelSoldAmount(0L);

    /** 最后一次重置时间 */
    private Date lastLockRestoredTime;


    /**
     *  判断是否有锁定库存   ---> 行为
     * @return
     */
    public boolean isLocked(){
        return Objects.nonNull(channelLockedStock);
    }


    public void addFrozenStock(ChannelFrozenStock frozenStock){
        channelFrozenStocks.add(frozenStock);
    }

    public List<ChannelFrozenStock> getFrozenStocksBySessionId(String sessionId){
        List<ChannelFrozenStock> result = new ArrayList<>();
        for(ChannelFrozenStock stock : channelFrozenStocks){
            if(stock.getSessionId().equals(sessionId)){
                result.add(stock);
            }
        }
        return result;
    }

    public List<ChannelFrozenStock> removeFrozenStocksBySessionId(String sessionId){
        List<ChannelFrozenStock> stocksTobeRemoved =  new ArrayList<>();
        for(ChannelFrozenStock stock : channelFrozenStocks){
            if(stock.getSessionId().equals(sessionId)){
                stocksTobeRemoved.add(stock);
            }
        }
        channelFrozenStocks.removeAll(stocksTobeRemoved);
        return stocksTobeRemoved;
    }



}
